package com.zhaodui.util.word;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;

/**
 * 鐢ㄤ簬澶勭悊XWPFTable瀛楃鏇挎崲鐨勫伐鍏风被
 * @author JianQiu
 */
public class XWPFTableHandler {
	
	private XWPFTable xwpfTable;
	private List<XWPFTableRow> xwpfTableRows;
	
	/**
	 * 鍒濆鍖朮WPFTable澶勭悊鍣�
	 * @param xwpfTable 寰呭鐞嗙殑瀵硅薄
	 */
	public XWPFTableHandler(XWPFTable xwpfTable){
		this.xwpfTable = xwpfTable;
		xwpfTableRows = xwpfTable.getRows();
	}
	
	/**
	 * 鑾峰彇鎵�鏈夌殑琛�
	 * @return 鍖呭惈浜嗚瀵硅薄鐨勯泦鍚�
	 */
	public List<XWPFTableRow> getRows(){
		return xwpfTableRows;
	}
	
	/**
	 * 鑾峰彇鎵�鏈夌殑cell
	 * @return 鍖呭惈浜哻ell鐨勯泦鍚�
	 */
	public List<XWPFTableCell> getCells(){
		List<XWPFTableCell> xwpfTableCells = new ArrayList<XWPFTableCell>();
		for(int i = 0 ; i < xwpfTableRows.size() ; i++){
			xwpfTableCells.addAll(getCells(i));
		}
		return xwpfTableCells;
	}
	
	/**
	 * 寰楀埌table涓寚瀹氳瀵瑰簲鐨刢ell闆嗗悎
	 * @param rowIndex 琛屾暟(浠�0寮�濮�)
	 * @return 鍖呭惈浜嗘寚瀹氳cell鐨勯泦鍚�
	 */
	public List<XWPFTableCell> getCells(int rowIndex){
		return xwpfTableRows.get(rowIndex).getTableCells();
	}
	
	/**
	 * 寰楀埌table涓墍鏈夌殑鏂囨湰鍐呭
	 * @return 
	 */
	public List<XWPFParagraph> getAllParagraphs(){
		List<XWPFTableCell> xwpfTableCells = getCells();
		List<XWPFParagraph> xwpfParagraphs = new ArrayList<XWPFParagraph>();
		for(XWPFTableCell cell : xwpfTableCells){
			xwpfParagraphs.addAll(cell.getParagraphs());
		}
		return xwpfParagraphs;
	}
	
	/**
	 * 鎵�鏈夊尮閰嶇殑鍊兼浛鎹负瀵瑰簲鐨勫��
	 * @param key(鍖归厤妯℃澘涓殑${key})
	 * @param value 鏇挎崲鍚庣殑鍊�
	 * @return
	 */
	public boolean replace(String key,String value){
		List<XWPFParagraph> allParagraphs = getAllParagraphs();
		boolean successReplace = false;
		for(XWPFParagraph xwpfParagraph : allParagraphs){
			XWPFParagraphHandler xwpfParagraphUtils = new XWPFParagraphHandler(xwpfParagraph);
			boolean currSuccessTag = xwpfParagraphUtils.replaceAll(key, value);
			successReplace = successReplace?successReplace:currSuccessTag;
		}
		return successReplace;
	}
	
	/**
	 * 鎵�鏈夊尮閰嶇殑鍊兼浛鎹负瀵瑰簲鐨勫��(key鍖归厤妯℃澘涓殑${key})
	 * @param param 瑕佹浛鎹㈢殑key-value闆嗗悎
	 * @return
	 */
	public boolean replace(Map<String,String> param){
		List<XWPFParagraph> allParagraphs = getAllParagraphs();
		boolean successReplace = false;
		for(XWPFParagraph xwpfParagraph : allParagraphs){
			XWPFParagraphHandler xwpfParagraphUtils = new XWPFParagraphHandler(xwpfParagraph);
			boolean currSuccessTag = xwpfParagraphUtils.replaceAll(param);
			successReplace = successReplace?successReplace:currSuccessTag;
		}
		return successReplace;
	}
	
}
